package cn.topcodes.tcsf.admin.jms;

import cn.topcode.unicorn.utils.JsonUtil;
import cn.topcode.unicorn.utils.dist.DistEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.util.Assert;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

/**
 * @author Unicorn
 */
public class JmsService {

    @Autowired
    private JmsTemplate jmsTemplate;

    public void sendJson(Destination destination, Object obj) {
        jmsTemplate.send(destination, buildMessageCreator(obj));
    }

    public void sendJson(Destination destination, DistEvent event) {
        jmsTemplate.send(destination, buildMessageCreator(event));
    }

    public static void sendJson(JmsTemplate jmsTemplate, Destination destination, Object obj) {
        jmsTemplate.send(destination, buildMessageCreator(obj));
    }

    public static void sendJson(JmsTemplate jmsTemplate, Destination destination, DistEvent event) {
        jmsTemplate.send(destination, buildMessageCreator(event));
    }

    public static MessageCreator buildMessageCreator(DistEvent event) {
        MessageCreator mc = new MessageCreator() {

            @Override
            public Message createMessage(Session session) throws JMSException {
                event.pack();
                return session.createTextMessage(event.toJson());
            }
        };
        return mc;
    }

    public static MessageCreator buildMessageCreator(Object obj) {
        Assert.notNull(obj, "obj不能为空");
        MessageCreator mc = new MessageCreator() {

            @Override
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(JsonUtil.toJson(obj));
            }
        };
        return mc;
    }
}
